const router = require("express").Router(); // 在express中使用Router实现模块拆分
const Model = require("../../../models/product");

router.get("/", async (req, res) => {
  const data = await Model.find({}).sort({ _id: -1 });
  res.json(data);
});

router.get("/:id", async (req, res) => {
  const data = await Model.findById(req.params.id);
  res.json(data);
});

router.post("/", async (req, res) => {
  const data = new Model(req.body);
  await data.save();
  res.json({
    code: 1,
    data: "保存成功",
  });
});

router.put("/:id", async (req, res) => {
  await Model.findByIdAndUpdate(req.params.id, req.body);
  res.json({
    code: 1,
    data: "修改成功",
  });
});

router.delete("/:id", async (req, res) => {
  await Model.findByIdAndDelete(req.params.id);
  res.json({
    code: 1,
    data: "删除成功",
  });
});

module.exports = router;
